define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, $stateParams, $sce, Pointgoods, $ionicSlideBoxDelegate, $window, $timeout, GoPage, GoDialog) {
		
		$scope.data = {
			count: 1,
			goods: null
		};

		//画面加载
		$scope.$on('$ionicView.afterEnter', function() {
			$scope.init_page($stateParams.id);
		}, false);

		//初始化
		$scope.init_page = function(goods_id) {
			Pointgoods.get_detail({
				'goods_id': goods_id,
			}, function(res) {
				console.log(res)
				if (res.success != true) {
					GoDialog.alert("提示",res.msg,function(){
						GoPage.go_back();
					});
					return;
				}

				$scope.data.goods = res.result || {};

				var images = [];
				for (var imgid in $scope.data.goods.images) {
					images.push($scope.data.goods.images[imgid]);
				}
				$scope.data.goods.images = images;

				$scope.data.goods.intro = $sce.trustAsHtml($scope.data.goods.intro);

				if ($scope.data.goods.permission=='false') {
					GoDialog.alert("提示","商品无法兑换",function(){
						GoPage.go_back();
					});
				}

				var pgtis_handle = $ionicSlideBoxDelegate.$getByHandle('advs-handle');
				pgtis_handle.update(); //解决无法加载
			    pgtis_handle.loop(true); //循环
			})
		}

		//加
		$scope.add = function(){
			if ($scope.data.count >= $scope.data.goods.store ||
				$scope.data.count >= $scope.data.goods.max_buy_store) {
				return;
			}
			$scope.data.count++;
		}
		//减
		$scope.reduce = function(){
			if($scope.data.count>1){
				$scope.data.count--;
			}
		}
		
		
		$scope.get_goods = function() {
			if ($scope.data.goods.permission=='false' || $scope.data.count <= 0) {
				return;
			}
			// 保存，“立即兑换”
			Pointgoods.set_gift_cart({
				'goods_id': $scope.data.goods.goods_id,
				'type': 'goods',
				'products': [
					{
						'goods_id': $scope.data.goods.goods_id,
						'product_id': $scope.data.goods.product_id,
						'num': $scope.data.count
					}
				],
				'num': $scope.data.count,
			}, function(res) {
				if (res.success != true) {
					GoDialog.toast(res.msg);
					return;
				}
				GoPage.go_states("pointorder", {
					'orderinfo': window.btoa(JSON.stringify({goods_id: $scope.data.goods.goods_id, num: $scope.data.count}))
				});
			})
		}
		
		
	}

	controller.$inject = ['$scope', '$stateParams', "$sce", 'Pointgoods', '$ionicSlideBoxDelegate', '$window', '$timeout','GoPage', 'GoDialog'];
	
	return app.registerController("pointgoodsctrl",controller);
});